package com.disease.chronic.Service.Impl;

import com.disease.chronic.Exception.ChronicExceptionEnum;
import com.disease.chronic.Global.Result;
import com.disease.chronic.Mappers.IndicatorsDetailMapper;
import com.disease.chronic.Service.DeepSeekService;
import com.disease.chronic.dto.AI.DeepSeekMessageDto;
import com.disease.chronic.dto.AI.DeepSeekRequestDto;
import com.disease.chronic.dto.AI.DeepSeekResponseDto;
import com.disease.chronic.pojo.IndicatorsDetail;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Headers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class DeepSeekServiceImpl implements DeepSeekService {
    @Value("${deepseek.key}")
    String key;
    @Value("${deepseek.url}")
    String url;

    @Value("${deepseek.model}")
    String model;

    @Autowired
    RedisTemplate<String,String> redisTemplate;



    @Autowired
    IndicatorsDetailMapper indicatorsDetailMapper;
    @Override
    public Result getSuggestion(String username, String indicatorName) {

        //设置必须请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Accept", "application/json");
        headers.add("Authorization", "Bearer "+key);

            DeepSeekRequestDto request = new DeepSeekRequestDto();
            request.setModel(model);

            //设置给AI的提示词
            DeepSeekMessageDto prompt = new DeepSeekMessageDto();
            prompt.setContent("你是一名专业医生,你需要分析我提供的一段时间内的"+indicatorName+"测量数值,给我一句简短的调理建议");
            prompt.setRole("system");

            //查询所有指标
            List<IndicatorsDetail> indicators = indicatorsDetailMapper.selectIndicatorByUsernameAndIndicatorName(username, indicatorName);

            //因为只取最近30条数据,自定义排序，让日期从大到小
            indicators.sort((o1,o2)->o2.getDay().compareTo(o1.getDay()));

            int count = 0; //计数判断是否超过30天，用户控制循环次数

            boolean flag = false; // 标识最近30天有没有测量

            StringBuilder message = new StringBuilder();
            for(IndicatorsDetail i:indicators){
                if(count++>30) break;
                if(i.getValue()!=null) flag = true;
                message.append(i.getDay().toString()).append(":").append(i.getValue());
            }
            if(!flag){
                return new Result(ChronicExceptionEnum.NO_MEASURE.getCode(),
                        ChronicExceptionEnum.NO_MEASURE.getMessage());
            }
            //设置传输给AI的数值
            DeepSeekMessageDto msg = new DeepSeekMessageDto(message.toString(),"user");

            List<DeepSeekMessageDto> list = new ArrayList<>();
            list.add(prompt);
            list.add(msg);
            request.setMessages(list);


        HttpEntity<DeepSeekRequestDto> entity =  new HttpEntity<>(request, headers);
        RestTemplate restTemplate = new RestTemplate();
        String content = "";
//        if(redisTemplate.opsForHash().hasKey(username+"suggest",username))
//            content = (String) redisTemplate.opsForHash().get(username+"suggest",username);
//        else{
            //发起请求并接受响应
            ResponseEntity<DeepSeekResponseDto> response = restTemplate.exchange(url, HttpMethod.POST, entity, DeepSeekResponseDto.class);
            content = response.getBody().getChoices().get(0).getMessage().getContent();
//            redisTemplate.opsForHash().put(username+"suggest",username,content);
//            redisTemplate.expire(username+"suggest",1, TimeUnit.SECONDS);
//        }

        return new Result(ChronicExceptionEnum.SUCCESS.getCode(),
                ChronicExceptionEnum.SUCCESS.getMessage(),content);
    }


    @Override
    public Result call(String message) {

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Accept", "application/json");
        headers.add("Authorization", "Bearer "+key);
        DeepSeekRequestDto request = new DeepSeekRequestDto();
        request.setModel(model);

        //设置给AI的提示词
        DeepSeekMessageDto prompt = new DeepSeekMessageDto();
        prompt.setContent("你是一名专门处理慢性病专业医生,你需要根据我的问题给予最简短的建议,回答要尽量快速而准确");
        prompt.setRole("system");

        //用户消息
        DeepSeekMessageDto userMessage = new DeepSeekMessageDto(message,"user");
        List<DeepSeekMessageDto> list = new ArrayList<>();

        list.add(prompt);
        list.add(userMessage);

        request.setMessages(list);
        HttpEntity<DeepSeekRequestDto> entity =  new HttpEntity<>(request, headers);
        RestTemplate restTemplate = new RestTemplate();
        //发起请求并接受响应
        ResponseEntity<DeepSeekResponseDto> response = restTemplate.exchange(url, HttpMethod.POST, entity, DeepSeekResponseDto.class);
        String content = response.getBody().getChoices().get(0).getMessage().getContent();

        return new Result(ChronicExceptionEnum.SUCCESS.getCode(),
                ChronicExceptionEnum.SUCCESS.getMessage(),content);
    }

    //同一时间执行3次函数，使用异步减少时间
    @Async
    @Override
    public CompletableFuture<Void> getDaySuggestion(String username, String suggest,
                                                    String[] strings, List<IndicatorsDetail> indicatorsDetails) {


        StringBuilder message = new StringBuilder();
        for(IndicatorsDetail i:indicatorsDetails){
            message.append(i.getIndicatorName()).append(":").append(i.getValue()).append(";");
        }

        HttpHeaders headers = getHeaders();

        DeepSeekRequestDto request = new DeepSeekRequestDto();
        request.setModel(model);

        //设置给AI的提示词
        DeepSeekMessageDto prompt = new DeepSeekMessageDto();
        prompt.setContent("你是一名专门处理慢性病专业医生,你需要根据我提供的各项数据提供简短的"+suggest+"建议,不要评价我的数据,回答格式为:"+suggest+":1. 2. 3. ");
        prompt.setRole("system");

        DeepSeekMessageDto userMessage = new DeepSeekMessageDto(message.toString(),"user");

        List<DeepSeekMessageDto> list = new ArrayList<>();
        list.add(prompt);
        list.add(userMessage);
        request.setMessages(list);
        HttpEntity<DeepSeekRequestDto> entity =  new HttpEntity<>(request, headers);
        RestTemplate restTemplate = new RestTemplate();
        //发起请求并接受响应
        ResponseEntity<DeepSeekResponseDto> response = restTemplate.exchange(url, HttpMethod.POST, entity, DeepSeekResponseDto.class);

        String content = response.getBody().getChoices().get(0).getMessage().getContent();

        if(content.startsWith("饮食")) strings[0] = content.substring(content.indexOf("1"));
        if(content.startsWith("作息")) strings[1] = content.substring(content.indexOf("1"));
        if(content.startsWith("运动")) strings[2] = content.substring(content.indexOf("1"));

        return CompletableFuture.completedFuture(null);
    }

    public HttpHeaders getHeaders(){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Accept", "application/json");
        headers.add("Authorization", "Bearer "+key);

        return headers;
    }


}
